﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Ccit.Utils;
using Ccit.OA.UserControls;
using Newtonsoft.Json;
using System.Collections.Generic;



namespace Ccit.OA.Email
{
    public partial class email_write : Ccit.Utils.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                ViewState["YJBZ"] = (null != Request.QueryString["YJBZ"]) ? Request.QueryString["YJBZ"].ToString() : "";
                hidYJBZ.Value = ViewState["YJBZ"].ToString();
                ViewState["YJID"] = (null != Request.QueryString["YJID"]) ? Request.QueryString["YJID"].ToString() : "";
                hidspace.Value = (null != Request.QueryString["Lastspace"]) ? Request.QueryString["Lastspace"].ToString() : "0";
                //Response.Write(ViewState["Lastspace"].ToString().Trim());
                InitPage();
            }
        }
        private void InitPage()
        {
            string sYJID = ViewState["YJID"].ToString().Trim();
            string sYJBZ = ViewState["YJBZ"].ToString().Trim();  //sYJBZ为C时为  "转发" 标志 A为回复
            lnbList.Attributes["onclick"] = "return moreEmail();";
            lntSend.Attributes["onclick"] = "return AddEmail();return false;";
            lntSave.Attributes["onclick"] = "return SaveEmails();return false;";
            LoginUser loginUser = Session["LogUserInfo"] as LoginUser;

            hidYGXH.Value = loginUser.UserId;
            hidYGJB.Value = loginUser.ClassId;
            hidYGBM.Value = loginUser.DeptId;
            hidYGZW.Value = loginUser.PosId;
            hidJG.Value = loginUser.OrganId;

            MsEmailDetails msDetails = new MsEmailDetails();
            EmailBLL bll = new EmailBLL();
            
            /*绑定签名记录*/
            MsEmailSigna msSigna = new MsEmailSigna();
            msSigna.userId = loginUser.UserId;
            DataSet dSetSign = bll.GetSigna(msSigna);
            ClearMenu(dSetSign);
            MsEmailAccount msAccount = new MsEmailAccount();
            msAccount.userId = loginUser.UserId;
            DataSet msAccountList = bll.GetAccountList(msAccount);
            
            WebEmailBing(msAccountList);


            //lbSigned.Attributes["onclick"] = "signClick();return false";
            //编辑邮件
            if (sYJID != "")
            {
                msDetails = bll.GetEmailDetails(sYJID);

                #region  参数绑定
                #region 当不为转发时 绑定下列参数
                if (sYJBZ != "C")
                {
                    if (sYJBZ != "A")
                    {
                        //内部收件人
                        txtNBSJR.Text = Ccit.OA.Utils.SysInterface.GetNameStrByIdStr(msDetails.nbsjRange, msDetails.nbsjlogo, " ");
                        hidNBSJRId.Value = msDetails.nbsjRange;
                        hidNBSJRType.Value = msDetails.nbsjlogo;

                        //内部抄送
                        txtNBCSR.Text = Ccit.OA.Utils.SysInterface.GetNameStrByIdStr(msDetails.nbcsRange, msDetails.nbcslogo, " ");
                        hidNBCSRId.Value = msDetails.nbcsRange;
                        hidNBCSRType.Value = msDetails.nbcslogo;

                        //内部密送
                        txtNBMSR.Text = Ccit.OA.Utils.SysInterface.GetNameStrByIdStr(msDetails.nbmjRange, msDetails.nbmjlogo, " ");
                        hidNBMSRId.Value = msDetails.nbmjRange;
                        hidNBMSRType.Value = msDetails.nbmjlogo;

                        btnClose.Visible = false;
                    }
                    else {
                        txtNBSJR.Text = Ccit.OA.Utils.SysInterface.GetNameStrByIdStr(msDetails.jjuserId, "0", " ");
                        hidNBSJRId.Value = msDetails.jjuserId;
                        hidNBSJRType.Value = "0";
                        btnBack.Visible = false; 
                    }
                }
                else { btnBack.Visible = false; }
                #endregion

                hidEMLID.Value = msDetails.emlId;     
                txtZT.Text = msDetails.emlTitle;
                TemplateContext.Text = msDetails.emlContent;
                ddlYXJB.SelectedValue = msDetails.emllevel;

                if (msDetails.readlogo == "1")
                {
                    TXBZ.Checked = true;
                }
                if (msDetails.saveflag == "1")
                {
                    SAVEFLAG.Checked = true;
                }
                
                #endregion

                #region 显示附件
                AttUpLoad.EditShow("999009", sYJID);
                #endregion
            }
            else
            {
                btnClose.Visible = false;
                for (int i = 0; i < dSetSign.Tables[0].Rows.Count; i++)
                {
                    if (dSetSign.Tables[0].Rows[i]["EML_A5_50"].ToString().Trim() == "1")
                    {
                        TemplateContext.Text = dSetSign.Tables[0].Rows[i]["EML_A5_40"].ToString().Trim();
                    }
                }
            }

            #region 根据配置参数判断是否可发送外部邮件
            ConfigLib oConfig = new ConfigLib();
            string ENDOUTEMAIL = oConfig.GetAttribute("CCIT_SYSTEM/CCIT_ISSENDOUTEMAIL", eValueType.TEXT);
            if (ENDOUTEMAIL== "")
            {
                ENDOUTEMAIL = "0";  
            }
            hidEndOutShow.Value = ENDOUTEMAIL;
            #endregion

            hidTime.Value = System.DateTime.Now.ToString();

            bll.Release();
            bll = null;
            msDetails = null;
            msSigna = null;
            msAccountList = null;
            
        }

         /// <summary>
        /// ajax方法 发送邮件
        /// </summary>
        /// <returns></returns>
        [global::System.Web.Services.WebMethod]
        public static string AddEmails(string serExpr, string attachXML, string handleSign,string wbyjbz)
        {
            bool bFlag = false;
            MsEmailDetails msdetails = (MsEmailDetails)JavaScriptConvert.DeserializeObject(serExpr, typeof(MsEmailDetails));
            EmailBLL bll = new EmailBLL();
            msdetails.sendtime = System.DateTime.Now.ToString();
            string oriRecId = msdetails.emlId;
            if (handleSign == "C")
            {
                msdetails.emlId = "";
            }

            if (msdetails.emlId == "")
            {
                msdetails = bll.SendEmail(msdetails);

                if (msdetails != null)
                {
                    bFlag = true;
                }
            }
            else {
                msdetails = bll.UpdateEmail(msdetails);

                if (msdetails != null)
                {
                    bFlag = true;
                }
            }


            /* 保存附件 */

            if (bFlag)
            {
                if (handleSign == "C")
                {
                    AttachUpLoad.CopyExistedAttaches("999009", oriRecId ,msdetails.emlId );

                }
                else
                {
                    AttachClass attClass = (AttachClass)Factory.CreateObject("Ccit.OA.UserControls.AttachUpLoad.dll", "Ccit.OA.UserControls.AttachClass",
                                ImportComponentType.DotNetDll, null);

                    bFlag = attClass.SaveAttaches("999009", msdetails.emlId, attachXML);
                    attClass = null;
                }

                #region 检查是否发送外部邮件
                if (msdetails.wbsjlist != "")
                {
                    SendWebEmail(wbyjbz, msdetails);
                }
                #endregion
            }


            string sResult = (bFlag) ? "1" : "0";

            var newObj = new {resultSign = sResult };
            string resultSerExpr = JavaScriptConvert.SerializeObject(newObj);

            bll.Release();
            bll = null;
            msdetails = null;

            return resultSerExpr;
        }

        [global::System.Web.Services.WebMethod]
        public static string AddSign(string serExpr)
        {
            bool bFlag = false;
            MsEmailDetails msdetails = (MsEmailDetails)JavaScriptConvert.DeserializeObject(serExpr, typeof(MsEmailDetails));
            EmailBLL bll = new EmailBLL();
            string sflag = msdetails.draftlogo;
            if (sflag == "4")
            {
                bFlag = true;
            }
            string sResult = (bFlag) ? "1" : "4";
            var newObj = new { resultText = msdetails.emlContent, resultSign = sResult };
            string resultSerExpr = JavaScriptConvert.SerializeObject(newObj);

            bll.Release();
            bll = null;
            return resultSerExpr;
        }
        /// <summary>
        /// 保存邮件
        /// </summary>
        /// <param name="serExpr"></param>
        /// <returns></returns>
        [global::System.Web.Services.WebMethod]
        public static string SaveEmails(string serExpr,string attachXML,string handleSign)
        {
            bool bFlag = false; 
            MsEmailDetails msdetails = (MsEmailDetails)JavaScriptConvert.DeserializeObject(serExpr, typeof(MsEmailDetails));
            EmailBLL bll = new EmailBLL();
            string oriRecId = msdetails.emlId;
            if (handleSign == "C")
            {
                msdetails.emlId = "";
            }
            if (msdetails.emlId == "")
            {
                msdetails = bll.SendEmail(msdetails);
                if (msdetails != null)
                {
                    bFlag = true;
                }
            }
            else
            {
                msdetails = bll.UpdateEmail(msdetails);
                if (msdetails != null)
                {
                    bFlag = true;
                }
            }

            /* 保存成功后保存附件记录信息 */
            if (bFlag)
            {
                if (handleSign == "C")
                {
                    AttachUpLoad.CopyExistedAttaches("999009", oriRecId,msdetails.emlId );

                }
                else
                {
                    AttachClass attClass = (AttachClass)Factory.CreateObject("Ccit.OA.UserControls.AttachUpLoad.dll", "Ccit.OA.UserControls.AttachClass",
                                ImportComponentType.DotNetDll, null);

                    bFlag = attClass.SaveAttaches("999009", msdetails.emlId, attachXML);
                    attClass = null;
                }
            }


            //保存成功时 为草稿类型1    失败时3(提示保存错误)
            string sResult = (bFlag) ? "1" : "3";
            msdetails.draftlogo = sResult;
            string resultSerExpr = JavaScriptConvert.SerializeObject(msdetails);

            bll.Release();
            bll = null;
            msdetails = null;

            return resultSerExpr;
        }


        public void ClearMenu(DataSet dSet)
        {
            LoginUser loginUser = Session["LogUserInfo"] as LoginUser;
            /*绑定签名记录*/
            if (dSet.Tables[0].Rows.Count != 0)
            {
                for (int i = 0; i < dSet.Tables[0].Rows.Count; i++)
                {
                    HtmlTableRow tRow = new HtmlTableRow();
                    HtmlTableCell tCell = new HtmlTableCell();
                    tRow.Align = "left";
                    //tCell.BgColor = "#D6D6D6";
                    tCell.Attributes.Add("Style","PADDING-RIGHT: 5px; PADDING-LEFT: 5px; PADDING-TOP: 5px; PADDING-BOTTOM: 5px;");
                    tCell.InnerHtml = "<a href=\"javascript:signClick('" + dSet.Tables[0].Rows[i]["EML_A5_40"].ToString().Trim() + "');\">" + dSet.Tables[0].Rows[i]["EML_A5_30"].ToString().Trim() + "</a>";
                    tRow.Cells.Add(tCell);
                    if (i != dSet.Tables[0].Rows.Count - 1)
                    {
                        tRow.Attributes.Add("Style", "BORDER-BOTTOM: window 2px inset;");
                    }
                    menuTable.Rows.Add(tRow);
                }
            }
            dSet = null;
        }

        public void WebEmailBing(DataSet msAccountList)
        {
            ddWBYX.Items.Clear();
            ddWBYX.DataSource = msAccountList;
            ddWBYX.DataTextField = "EML_A4_30";
            ddWBYX.DataValueField = "EML_A4_10";
            ddWBYX.DataBind();
            msAccountList = null;
        }


        /// <summary>
        /// 发送外部邮件
        /// </summary>
        /// <param name="strId">所有SMTP服务器 唯一ID</param>
        /// <param name="msDetails">邮件内容 消息对象</param>
        /// <returns>外部邮件发送结果 -999失败 / 01网络连接失败 / 1发送成功</returns>
        public static string SendWebEmail(string strId,MsEmailDetails msDetails)
        {
            string Return = string.Empty;
            MsEmailAccount msAccount = new MsEmailAccount();
            msAccount.Id = strId;
            EmailBLL bll = new EmailBLL();
            msAccount = bll.GetAccount(msAccount);

            if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable() == false)
            {
                Return = "01";
            }

            EmailLib emailObj = new EmailLib();
            emailObj.SenderEmail = msAccount.address;   //发件人的邮箱
            emailObj.Account = msAccount.pop3LogName;  //发件人邮箱账户
            emailObj.Password = msAccount.pop3Pass;   //发件人密码

            emailObj.ReceiveEmails = msDetails.wbsjlist;  //收件人的邮箱，多个由分号隔开
            if (msDetails.wbcslist != "")
            {
                emailObj.ReceiveEmails += ";" + msDetails.wbcslist;
            }
            if (msDetails.wbmslist != "")
            {
                emailObj.ReceiveEmails += ";" + msDetails.wbmslist;                
            }
            emailObj.MailSubject = msDetails.emlTitle;   //发送主题
            emailObj.Priority = System.Web.Mail.MailPriority.Low;  //发送优先级
            emailObj.MailContent = msDetails.emlContent; //邮件内容
            emailObj.MailFormat = System.Web.Mail.MailFormat.Text;  //发送格式，以文本形式发送

            emailObj.SMTPServer = msAccount.receiveSMTP;   //SMTP服务器

            #region 发送附件代码
            AttachClass attClass = (AttachClass)Factory.CreateObject("Ccit.OA.UserControls.AttachUpLoad.dll", "Ccit.OA.UserControls.AttachClass",
                            ImportComponentType.DotNetDll, null);

            List<string> lstAttach = attClass.SaveAttachToServer("999009", msDetails.emlId);

            // 赋值给发送邮件消息对象的AttachList属性
            emailObj.AttachList = lstAttach;
            #endregion

            List<string> lstSender = emailObj.Send();
            //清楚保存在服务器上的附件

            attClass.DeleteAttachesInServer(lstAttach);
            lstSender[0] = Return;

            msDetails = null;
            return Return;
        }

    }
}
